package com.huafeng.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huafeng.config.BotPropertiesConfig;
import com.huafeng.constant.MessageConstant;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * @author 花风
 * @date 2023/4/6 21:47
 * @Description 消息工具类
 */
@Slf4j
public class MessageUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final BotPropertiesConfig botProperties = SpringContextUtils.getBean(BotPropertiesConfig.class);
    public static final String BASE_URL = "http://localhost:" + botProperties.getPort();
    /**
     * 发送消息
     * @param content 消息的内容
     * @param id 好友QQ号 或 群号
     * @param type 类型(private,group)
     * @return 发送消息后的响应结果
     */
    public static Object sendMessage(String content,String id,String type){
        Object result = null;
        String url = BASE_URL;

        Map<String,Object> params = new HashMap<>();
        params.put("message",content);

        if ("private".equals(type)){
            params.put("user_id",id);
            url += MessageConstant.SEND_PRIVATE_URL;
            result = HttpUtils.doGet(url,params);

        }else if ("group".equals(type)){
            params.put("group_id",id);
            url += MessageConstant.SEND_GROUP_URL;
            result = HttpUtils.doGet(url,params);

        }else {
            throw new NoSuchElementException("type is illegal");
        }

        return result;
    }

    /**
     * 通过messageId获取消息
     * @param messageId 消息Id
     * @return 该Id对应的消息内容
     */
    public static String getMessage(String messageId){
        String res = "";
        try {
            String url = BASE_URL + "/get_msg?message_id=" + messageId;
            String result = HttpUtils.doGet(url);
            JsonNode readTree = objectMapper.readTree(result);

            //获取消息发送者账号信息
            String userId = readTree.get("data").get("sender").get("user_id").asText();
            res += "账号为：" + userId + "\n";
            //获取消息发送者的信息
            String nickname = readTree.get("data").get("sender").get("nickname").asText();
            res += "用户名为：" + nickname + "\n";
            //获取消息内容
            String message = readTree.get("data").get("message").asText();
            res += "撤回的消息为：" + message + "\n";

        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return res;
    }
}
